package com.dc.android_can.can;

import android.util.Log;

import com.dc.android_can.CAN;

import java.io.File;
import java.util.Arrays;


/**
 * Copyright (c) 2016--2019/1/22  Hunan Cnbot Co., Ltd. All Rights Reserved.
 *
 * @descriptoin  CAN 操作工具类
 * @FileName: CanUtils.java
 * @author: dc
 * @date: 2019/1/22 13:51
 * @version: 1.0
 */

public class CanUtils {
	private static final String TAG = CanUtils.class.getSimpleName();


    /**
     * 打开can通信设备
     * @return
     */
	public static boolean initDevice() {
		File spidev = new File("/dev/spidev0.0");
		File spiDevice = new File("/dev/SPI_INTERRUPT_AND_CS_CONTROL");

		boolean flag = openDeviceInternal(spidev);
		if (!flag) {
			return false;
		}
		else {
			flag = openDeviceInternal(spiDevice);
		}
		return flag;

	}

	/**
	 * 通过命令行打开设备
	 * @param device
	 * @return
	 */
	private static boolean openDeviceInternal(File device) {
		if (!device.canRead() || !device.canWrite()) {
			try {
				/* Missing read/write permission, trying to chmod the file */
				Process su;
				su = Runtime.getRuntime().exec("/system/xbin/su");
				String cmd = "chmod 6666 " + device.getAbsolutePath() + "\n" + "exit\n";
				su.getOutputStream().write(cmd.getBytes());
				if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
					return false;
				}
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	/**
	 * @descriptoin	向CAN总线写数据
	 * @author	dc
	 * @param sendData 需要写入的数据
	 *                 @param len 数据部分长度
	 * @date 2018/6/6 10:49
	 * @return > 0 写成功
	 * 如果CAN初始化失败写入数据会返回-1
	 * 或者健康板、环境板、电池板没有连接
	 */
	public static int canWrite(byte[] sendData, int len) {
		int sendResult = 0;
		if (sendData.length > 0) {
			Log.e(TAG, "发送数据" + Arrays.toString(sendData));
			sendResult = CAN.Write(0, sendData, len);
		}
		return sendResult;
	}

	/**
	 * @descriptoin	读取CAN总线数据
	 * @author	dc
	 * @date 2018/6/6 10:54
	 * @return null 无数据
	 */
	public static CanDataType canRead() {
		return CAN.ReadConDataType();
	}

}
